package com.seckill.item.service.impl;

import com.seckill.common.utils.BeanUtils;
import com.seckill.item.constants.RedisContants;
import com.seckill.item.domian.dto.ItemSeckillDTO;
import com.seckill.item.domian.po.ItemSeckill;
import com.seckill.item.mapper.ItemSeckillMapper;
import com.seckill.item.service.IItemSeckillService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.ZoneId;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 秒杀商品表 服务实现类
 * </p>
 *
 * @author zsc
 * @since 2025-05-20
 */
@Service
@RequiredArgsConstructor
public class ItemSeckillServiceImpl extends ServiceImpl<ItemSeckillMapper, ItemSeckill> implements IItemSeckillService {

    private final StringRedisTemplate redisTemplate;

    @Override
    @Transactional
    public void add(ItemSeckillDTO itemSeckillDTO) {
        //1. 新增秒杀商品
        ItemSeckill itemSeckill = BeanUtils.copyProperties(itemSeckillDTO, ItemSeckill.class);
        save(itemSeckill);
        //2. 增加 redis 缓存,同时设置过期时间为活动结束后的24小时
        String key = RedisContants.HOTSPOT_CACHE_KEY_PREFIX + itemSeckill.getId();
        //2.1将itemSeckill对象转为map
        Map<String,String> map = new HashMap<>();
        map.put("id",itemSeckill.getId().toString());
        map.put("itemId",itemSeckill.getItemId().toString());
        map.put("seckillPrice",itemSeckill.getSeckillPrice().toString());
        map.put("seckillStock",itemSeckill.getSeckillStock().toString());
        map.put("startTime",itemSeckill.getStartTime().toString());
        map.put("endTime",itemSeckill.getEndTime().toString());
        map.put("limitNum",itemSeckill.getLimitNum().toString());
        //2.2将map存入redis，同时设置过期时间为活动结束后的24小时键为key，值为map
        redisTemplate.opsForHash().putAll(key, map);
        //2.3计算过期时间，秒杀活动结束的时间减去当前时间在加上24小时
        long expireTime = itemSeckill.getEndTime().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli() -  System.currentTimeMillis() + TimeUnit.HOURS.toMillis(24);
        redisTemplate.expire(key, expireTime, TimeUnit.MILLISECONDS);
        //todo 3.将页面静态化

    }
}
